<template>
  <div class="product-carousel-management">
    <el-card>
      <div slot="header" class="clearfix header-container">
        <span class="page-title">
          <i class="el-icon-picture-outline"></i>
          APP商品轮播管理
        </span>
        <div class="header-actions">
          <el-button type="text" @click="loadData">刷新数据</el-button>
        </div>
      </div>

      <!-- 说明 -->
      <el-alert
        title="功能说明"
        type="info"
        :closable="false"
        style="margin-bottom: 20px">
        <template slot>
          <p>选择商品设置为APP首页轮播展示，可拖拽调整轮播顺序，最多支持设置10个轮播商品。</p>
        </template>
      </el-alert>

      <!-- 当前轮播商品 -->
      <div class="carousel-section">
        <div class="section-header">
          <h3>
            <i class="el-icon-star-on"></i>
            当前轮播商品
            <el-tag type="success" size="small" style="margin-left: 10px">{{ carouselList.length }}/10</el-tag>
          </h3>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="showSelectDialog"
            :disabled="carouselList.length >= 10">
            添加轮播商品
          </el-button>
        </div>

        <div v-if="carouselList.length > 0" class="carousel-list">
          <draggable
            v-model="carouselList"
            :options="{ animation: 200 }"
            @end="handleDragEnd"
            class="draggable-container">
            <transition-group name="flip-list" tag="div" class="carousel-grid">
              <div
                v-for="(item, index) in carouselList"
                :key="item.id"
                class="carousel-item">
                <div class="carousel-card">
                  <!-- 排序标识 -->
                  <div class="sort-badge">{{ index + 1 }}</div>

                  <!-- 商品图片 -->
                  <div class="product-image">
                    <img v-if="item.images" :src="item.images" :alt="item.name" />
                    <div v-else class="no-image">
                      <i class="el-icon-picture-outline"></i>
                      <span>暂无图片</span>
                    </div>
                  </div>

                  <!-- 商品信息 -->
                  <div class="product-info">
                    <div class="product-name" :title="item.name">{{ item.name }}</div>
                    <div class="product-price">¥{{ formatPrice(item.price) }}</div>
                    <div class="product-meta">
                      <span class="meta-item">
                        <i class="el-icon-box"></i>
                        库存: {{ item.num }}
                      </span>
                      <span class="meta-item">
                        <i class="el-icon-s-shop"></i>
                        {{ item.merchantName || '未知商家' }}
                      </span>
                    </div>
                  </div>

                  <!-- 操作按钮 -->
                  <div class="carousel-actions">
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-delete"
                      class="remove-btn"
                      @click="handleRemove(item)">
                      移除
                    </el-button>
                  </div>

                  <!-- 拖拽提示 -->
                  <div class="drag-handle">
                    <i class="el-icon-rank"></i>
                  </div>
                </div>
              </div>
            </transition-group>
          </draggable>
        </div>

        <el-empty
          v-else
          description="暂无轮播商品，点击上方按钮添加"
          :image-size="120">
        </el-empty>
      </div>
    </el-card>

    <!-- 选择商品对话框 -->
    <el-dialog
      title="选择商品"
      :visible.sync="selectDialogVisible"
      width="1200px"
      :close-on-click-modal="false"
      top="5vh"
      custom-class="action-dialog">

      <!-- 搜索筛选 -->
      <div class="dialog-search">
        <el-form :model="searchForm" :inline="true">
          <el-form-item label="商品名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入商品名称"
              clearable
              style="width: 200px">
            </el-input>
          </el-form-item>
          <el-form-item label="商家名称">
            <el-input
              v-model="searchForm.merchantName"
              placeholder="请输入商家名称"
              clearable
              style="width: 200px">
            </el-input>
          </el-form-item>
          <el-form-item label="商品状态">
            <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width: 120px">
              <el-option label="全部" :value="null"></el-option>
              <el-option label="上架" :value="1"></el-option>
              <el-option label="下架" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearchProduct">查询</el-button>
            <el-button icon="el-icon-refresh" @click="handleResetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 商品列表 -->
      <configurable-table
        :columns="productColumns"
        :data="productList"
        :loading="productLoading"
        :show-pagination="true"
        :current-page.sync="pagination.current"
        :page-size.sync="pagination.size"
        :pagination-total="pagination.total"
        @page-change="loadProductList"
        border
        stripe>

        <!-- 商品图片列 -->
        <template #picture="{ row }">
          <div class="table-product-image">
            <img v-if="row.images" :src="row.images" :alt="row.name" />
            <div v-else class="no-image-small">
              <i class="el-icon-picture-outline"></i>
            </div>
          </div>
        </template>

        <!-- 价格列 -->
        <template #price="{ row }">
          <span class="price-text">¥{{ formatPrice(row.price) }}</span>
        </template>

        <!-- 状态列 -->
        <template #status="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'" size="small">
            {{ row.status === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>

        <!-- 操作列 -->
        <template #actions="{ row }">
          <el-button
            size="mini"
            type="primary"
            :disabled="isProductInCarousel(row.id) || carouselList.length >= 10"
            @click="handleAddToCarousel(row)">
            {{ isProductInCarousel(row.id) ? '已添加' : '添加到轮播' }}
          </el-button>
        </template>
      </configurable-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="selectDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import {
  getCarouselList,
  markCarousel,
  updateCarouselSort,
  getAllProductList
} from '@/api/aggregation'

export default {
  name: 'ProductCarouselManagement',
  components: {
    draggable
  },
  data() {
    return {
      loading: false,
      carouselList: [],

      // 选择商品对话框
      selectDialogVisible: false,
      productLoading: false,
      productList: [],

      // 搜索表单
      searchForm: {
        name: '',
        merchantName: '',
        status: null
      },

      // 分页
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },

      // 商品列表列配置
      productColumns: [
        { prop: 'id', label: 'ID', width: 80, align: 'center' },
        { prop: 'picture', label: '商品图片', width: 100, align: 'center', slot: 'picture' },
        { prop: 'name', label: '商品名称', minWidth: 200, showOverflowTooltip: true },
        { prop: 'price', label: '价格', width: 120, align: 'center', slot: 'price' },
        { prop: 'num', label: '库存', width: 100, align: 'center' },
        { prop: 'merchantName', label: '商家名称', minWidth: 150, showOverflowTooltip: true },
        { prop: 'status', label: '状态', width: 100, align: 'center', slot: 'status' },
        { prop: 'actions', label: '操作', width: 150, align: 'center', slot: 'actions', fixed: 'right' }
      ]
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 加载数据
    async loadData() {
      await this.loadCarouselList()
    },

    // 加载轮播列表
    async loadCarouselList() {
      this.loading = true
      try {
        Logger.log('=== 加载轮播商品列表 ===')
        const response = await getCarouselList()
        Logger.log('轮播列表API响应:', response)

        if (response.code === 0) {
          // 按 carousel_sort 排序（数值越小越靠前）
          this.carouselList = (response.data || []).sort((a, b) => {
            const sortA = a.carousel_sort || a.carouselSort || 0
            const sortB = b.carousel_sort || b.carouselSort || 0
            return sortA - sortB
          })
          Logger.log('排序后的轮播列表:', this.carouselList)
        } else {
          this.$message.error(response.msg || '加载轮播列表失败')
          this.carouselList = []
        }
      } catch (error) {
        Logger.error('加载轮播列表失败:', error)
        this.$message.error('加载轮播列表失败')
        this.carouselList = []
      } finally {
        this.loading = false
      }
    },

    // 显示选择商品对话框
    showSelectDialog() {
      if (this.carouselList.length >= 10) {
        this.$message.warning('最多只能设置10个轮播商品')
        return
      }
      this.selectDialogVisible = true
      this.loadProductList()
    },

    // 加载商品列表
    async loadProductList() {
      this.productLoading = true
      try {
        Logger.log('=== 加载商品列表 ===')

        const params = {
          pageIndex: this.pagination.current,
          pageSize: this.pagination.size
        }

        // 添加搜索条件
        if (this.searchForm.name) {
          params.name = this.searchForm.name
        }
        if (this.searchForm.merchantName) {
          params.merchantName = this.searchForm.merchantName
        }
        if (this.searchForm.status !== null && this.searchForm.status !== undefined) {
          params.status = this.searchForm.status
        }

        Logger.log('请求参数:', params)
        const response = await getAllProductList(params)
        Logger.log('商品列表API响应:', response)

        if (response.code === 0) {
          this.productList = response.data.list || []
          this.pagination.total = response.data.total || 0
        } else {
          this.$message.error(response.msg || '加载商品列表失败')
          this.productList = []
          this.pagination.total = 0
        }
      } catch (error) {
        Logger.error('加载商品列表失败:', error)
        this.$message.error('加载商品列表失败')
        this.productList = []
        this.pagination.total = 0
      } finally {
        this.productLoading = false
      }
    },

    // 搜索商品
    handleSearchProduct() {
      this.pagination.current = 1
      this.loadProductList()
    },

    // 重置搜索
    handleResetSearch() {
      this.searchForm = {
        name: '',
        merchantName: '',
        status: null
      }
      this.pagination.current = 1
      this.loadProductList()
    },

    // 添加到轮播
    async handleAddToCarousel(product) {
      if (this.carouselList.length >= 10) {
        this.$message.warning('最多只能设置10个轮播商品')
        return
      }

      if (this.isProductInCarousel(product.id)) {
        this.$message.warning('该商品已在轮播列表中')
        return
      }

      try {
        Logger.log('=== 添加商品到轮播 ===')
        Logger.log('商品ID:', product.id)

        const response = await markCarousel({
          productId: product.id,
          isCarousel: 1
        })
        Logger.log('添加轮播API响应:', response)

        if (response.code === 0) {
          this.$message.success('添加成功')
          await this.loadCarouselList()
        } else {
          this.$message.error(response.msg || '添加失败')
        }
      } catch (error) {
        Logger.error('添加轮播失败:', error)
        this.$message.error('添加失败')
      }
    },

    // 移除轮播
    async handleRemove(item) {
      try {
        await this.$confirm('确认要移除该轮播商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        Logger.log('=== 移除轮播商品 ===')
        Logger.log('商品ID:', item.productId)

        const response = await markCarousel({
          productId: item.id,
          isCarousel: 0
        })
        Logger.log('移除轮播API响应:', response)

        if (response.code === 0) {
          this.$message.success('移除成功')
          await this.loadCarouselList()
        } else {
          this.$message.error(response.msg || '移除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          Logger.error('移除轮播失败:', error)
          this.$message.error('移除失败')
        }
      }
    },

    // 拖拽结束
    async handleDragEnd() {
      try {
        Logger.log('=== 更新轮播排序 ===')

        // 构建排序数据 - API: /agg/carousel/updateSort
        // 参数格式: { list: [{id, sort}] }
        const sortData = this.carouselList.map((item, index) => ({
          id: item.id,
          sort: index + 1  // 从1开始，数值越小越靠前
        }))

        Logger.log('排序数据:', sortData)

        const response = await updateCarouselSort({ list: sortData })
        Logger.log('更新排序API响应:', response)

        if (response.code === 0) {
          this.$message.success('排序更新成功')
        } else {
          this.$message.error(response.msg || '排序更新失败')
          // 失败后重新加载
          await this.loadCarouselList()
        }
      } catch (error) {
        Logger.error('更新排序失败:', error)
        this.$message.error('排序更新失败')
        // 失败后重新加载
        await this.loadCarouselList()
      }
    },

    // 判断商品是否已在轮播中
    isProductInCarousel(productId) {
      return this.carouselList.some(item => item.productId === productId || item.id === productId)
    },

    // 格式化价格
    formatPrice(price) {
      if (price === null || price === undefined) return '0.00'
      return Number(price).toFixed(2)
    }
  }
}
</script>

<style scoped>
.product-carousel-management {
  padding: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-container::after{
  display: none;
}


.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 轮播区域 */
.carousel-section {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.section-header h3 i {
  margin-right: 8px;
  color: #f7ba2a;
  font-size: 18px;
}

/* 轮播列表 */
.carousel-list {
  min-height: 200px;
}

.draggable-container {
  width: 100%;
}

.carousel-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.carousel-item {
  position: relative;
}

.carousel-card {
  position: relative;
  background: #fff;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: move;
}

.carousel-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  transform: translateY(-2px);
}

/* 排序标识 */
.sort-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

/* 商品图片 */
.product-image {
  width: 100%;
  height: 200px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #c0c4cc;
}

.no-image i {
  font-size: 48px;
}

.no-image span {
  font-size: 14px;
}

/* 商品信息 */
.product-info {
  padding: 15px;
}

.product-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
  margin-bottom: 10px;
}

.product-meta {
  display: flex;
  flex-direction: column;
  gap: 5px;
  font-size: 12px;
  color: #909399;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.meta-item i {
  font-size: 14px;
}

/* 操作按钮 */
.carousel-actions {
  padding: 10px 15px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: center;
}

.remove-btn {
  color: #f56c6c !important;
}

.remove-btn:hover {
  background-color: #fef0f0;
}

/* 拖拽提示 */
.drag-handle {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 32px;
  height: 32px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  cursor: move;
  z-index: 10;
}

/* 拖拽动画 */
.flip-list-move {
  transition: transform 0.3s;
}

/* 对话框搜索区域 */
.dialog-search {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 6px;
}

.dialog-search .el-form-item {
  margin-bottom: 0;
}

/* 表格中的商品图片 */
.table-product-image {
  width: 60px;
  height: 60px;
  margin: 0 auto;
  border-radius: 6px;
  overflow: hidden;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.table-product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image-small {
  color: #c0c4cc;
  font-size: 24px;
}

.price-text {
  font-weight: 600;
  color: #f56c6c;
}

/* 响应式 */
@media (max-width: 1200px) {
  .carousel-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
}

@media (max-width: 768px) {
  .carousel-grid {
    grid-template-columns: 1fr;
  }
}

/* 对话框底部样式已移至公共样式 dialog.scss */
</style>

